//
//  MainViewController.swift
//  EyeVisionForPatients
//
//  Created by PMC on 2020/2/7.
//  Copyright © 2020 tao Tao. All rights reserved.
//

import UIKit
import HandyJSON
import SwiftyJSON

class CustomTabBar: UITabBar {
    
    var itemFrames = [CGRect]()
    var tabBarItems = [UIView]()
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        if itemFrames.isEmpty, let UITabBarButtonClass = NSClassFromString("UITabBarButton") {
            tabBarItems = subviews.filter { $0.isKind(of: UITabBarButtonClass) }
            tabBarItems.forEach { itemFrames.append($0.frame) }
        }
        
        if !itemFrames.isEmpty, !tabBarItems.isEmpty, itemFrames.count == items?.count {
            tabBarItems.enumerated().forEach { $0.element.frame = itemFrames[$0.offset] }
        }
    }
}

class MainViewController: UITabBarController {
    
    /// 消息model
    var messageModel = ReceiveModel()
    
    private var pickupView: PickupVideoView?
    
    private var isSelfLeave: Bool = false
    
    private var isFromUMPush: Bool = false
    
    private var isMeeting: Bool = false
    
    override var shouldAutorotate: Bool {
        return false
    }
    
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .portrait
    }
    
    override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
        return .portrait
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        if #available(iOS 15.0, *) {
            let appearance = UITabBarAppearance()
            appearance.backgroundColor = .white
            appearance.stackedLayoutAppearance.normal.titleTextAttributes = [.foregroundColor: UIColor(hex: "666666"), .font: UIFont.regular(12)]
            appearance.stackedLayoutAppearance.selected.titleTextAttributes = [.foregroundColor: UIColor(hex: "4D7CFA"), .font: UIFont.regular(12)]
            appearance.shadowColor = .clear
            UITabBar.appearance().standardAppearance = appearance
            UITabBar.appearance().scrollEdgeAppearance = appearance
        } else {
            UITabBar.appearance().barTintColor = .white
            UITabBar.appearance().shadowImage = UIImage()
            UITabBarItem.appearance().setTitleTextAttributes(
                [.foregroundColor: UIColor.textLight, .font: UIFont.regular(12)],
                for: .normal
            )
            UITabBarItem.appearance().setTitleTextAttributes(
                [.foregroundColor:UIColor.mainColor, .font: UIFont.regular(12)],
                for: .selected
            )
        }
        
        setValue(CustomTabBar(), forKey: "tabBar")
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        if !UserDefaults.token.isEmpty {
            WebSocketManager.shared().connect()
        }
        
        NotificationCenter.default.addObserver(self, selector: #selector(receiveMessage(_:)), name: NotiName.receiveMessage, object: nil)
        // 监听支付完成跳转
        NotificationCenter.default.addObserver(self, selector: #selector(surePayResult(_:)), name: NotiName.surePayResult, object: nil)
        // 推送消息跳转
        NotificationCenter.default.addObserver(self, selector: #selector(umpushMessage(_:)), name: NotiName.umpushMessage, object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(hideKeyboard), name: Notification.Name("hideKeyboard"), object: nil)
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        NotificationCenter.default.removeObserver(self)
    }
}

// MARK: - 监听事件
extension MainViewController {
    @objc func surePayResult(_ noti: Notification) {
        selectedIndex = 1
        guard let orderType = noti.object as? OrderType else { return }
        
        let selectedVc = selectedViewController as? ConsultationRoomController
        let index = orderType == .advisory ? 0 : 1
        selectedVc?.segmented.selectItemAt(index: index)
    }
    
    @objc func receiveMessage(_ noti: Notification) {
        guard let message = noti.object as? String else { return }
        
        if let model = ReceiveModel.deserialize(from: message) {
            /// 离线消息-结束咨询
            if model.command == 20 {
                let json = JSON(parseJSON: message)
                guard let data = json["data"]["friends"].description.data(using: .utf8),
                    let paras = try? JSONSerialization.jsonObject(with: data,
                                                                  options: .mutableContainers) as? [String: [Any]] else { return }
                for value in paras.values {
                    if let ms = [ReceiveModel].deserialize(from: value) as? [ReceiveModel] {
                        ms.forEach {
                            if $0.cmd == 101 { // 结束咨询离线消息
                                showAlert($0,.advisory)
                            }else if $0.cmd == 209 { // 结束护士预约咨询离线消息
                                showAlert($0,.nurse)
                            }  else if $0.cmd == 100 { // 视频请求离线消息
                                self.messageModel = $0

                                if isFromUMPush { return }
                                
                                YSGLog("离线视频请求: \(isFromUMPush), \(messageModel)")
                                
                                if isMeeting {
                                    WebSocketManager.shared().sendMessageForVideo(cmd: 30,
                                                                                  msgId: Date.milliStamp + String.randomOfFive,
                                                                                  diagnoseId: model.diagnoseId,
                                                                                  from: UserDefaults.userId,
                                                                                  to: model.doctorUserId)
                                } else {
                                    hideKeyboard()
                                }
                            }
                        }
                    }
                }
            }
            
            if model.cmd == 100 {
                self.messageModel = model
                YSGLog("正常视频消息: \(isFromUMPush), \(messageModel), \(isMeeting)")
                if isMeeting {
                    WebSocketManager.shared().sendMessageForVideo(cmd: 30,
                                                                  msgId: Date.milliStamp + String.randomOfFive,
                                                                  diagnoseId: model.diagnoseId,
                                                                  from: UserDefaults.userId,
                                                                  to: model.doctorUserId)
                } else {
                    hideKeyboard()
                }
            }
            
            /// 接收消息
            if model.command == 11 {
                guard let msgModel = model.data else { return }
                
                WebSocketManager.shared().sendMsgToServe(msgModel.id ?? "")
            }
            
            /// 医生请求结束诊断
            if model.cmd == 101 ||
                model.cmd == 107 ||
                model.cmd == 108 ||
                model.cmd == 109 ||
                model.cmd == 209 ||
                model.cmd == 208 ||
                model.cmd == 110 ||
                model.cmd == 112 {
                WebSocketManager.shared().sendMsgToServe(model.id)
            }
            
            /// 医生请求结束图文咨询
            if model.cmd == 101 {
                showAlert(model,.advisory)
            }else if model.cmd == 209 {
                // 护士请求结束咨询订单
                showAlert(model,.nurse)
            }
            
            /// 账号被顶
            if model.cmd == 106 {
                WebSocketManager.destroy()
                if isMeeting {
                    MeetingManager.shared.endMeeting()
                }
                AppDelegate.logout(inSelf: false)
            }
            
            if model.cmd == 105 {
                YSGLog("医生结束会议 105: \(isSelfLeave) - isMeeting: \(isMeeting)")
                
                if !isSelfLeave {
                    pickupView?.dismiss()
                    HUDTool.show(message: "医生已挂断视频")
                    MeetingManager.shared.endMeeting()
                }
            }
            
            /// 短信审核
            if model.cmd == 104 {
                WebSocketManager.shared().sendMsgToServe(model.id)
                HUDTool.show(message: "短信审核完成")
            }
            
            /// 处方审核通过
            if model.cmd == 107 {
                HUDTool.show(message: "处方已通过审核")
            }
            
            /// 医生接受图文咨询
            if model.cmd == 108 {
                HUDTool.show(message: "医生已接诊，可以开始与医生沟通", position: .top)
            }
            
            /// 护士接受护理咨询
            if model.cmd == 208 {
                HUDTool.show(message: "护士已接受咨询，可以开始与护士沟通", position: .top)
            }
            
            /// 医生拒绝图文咨询
            if model.cmd == 109 {
                HUDTool.show(message: "医生拒绝图文咨询")
            }
            
            /// 医生开处方后显示
//            if model.cmd == 112 {
//                HUDTool.show(message: "医生正在开处方，大约需要等待5分钟")
//            }
        }
    }
    
    @objc private func umpushMessage(_ noti: Notification) {
        isFromUMPush = true
        YSGLog("友盟视频推送: \(isFromUMPush)")
        guard let model = YSGNotiMessageModel.deserialize(from: noti.userInfo as? [String: Any]) else { return }
        YSGLog("后台 model: \(model)")
        switch model.pushType {
        case .chat, .prescription: pushConsultationRoomVc(at: 0)
        case .video: getYSXVideoInfo(model)
        case .cloud: pushConsultationRoomVc(at: 1)
        case .rejectAdvisory: pushOrderCancelList()
        case .endMeeting:
            if !isSelfLeave {
                HUDTool.show(message: "医生已挂断视频")
                MeetingManager.shared.endMeeting()
            }
            
            pickupView?.dismiss()
        default: break
        }
    }
    
    @objc private func hideKeyboard() {
        mainWindow.endEditing(true)
    }
    
    @objc private func ysxSDKLoginSuccess(_ noti: Notification) {
        guard let model = noti.object as? ReceiveModel else { return }
        messageModel = model
        showPickupVideoView(model)
    }
    
    @objc private func endVideo() {
        self.isSelfLeave = true
        endMeeting(messageModel)
    }
}

// MARK: - Helpers
extension MainViewController {
    private func createButton(image: String, action: Selector) -> UIButton {
        let button = UIButton(type: .custom)
        button.setImage(UIImage(named: image), for: .normal)
        button.addTarget(self, action: action, for: .touchUpInside)
        button.sizeToFit()
        return button
    }
    
    private func createButton(title: String, action: Selector) -> UIButton {
        let button = UIButton(type: .custom)
        button.setTitle(title, for: .normal)
        button.setTitleColor(.red, for: .normal)
        button.setTitleColor(.systemPink, for: .highlighted)
        button.titleLabel?.font = .medium(16)
        button.addTarget(self, action: action, for: .touchUpInside)
        return button
    }
    
    
    private func showAlert(_ model: ReceiveModel,_ status : chatStatusEnum) {
        AlertTool.showAlert(self,
                            message: "医生已出具诊断意见，若您没有其它问题，请确认是否结束问诊?",
                            sureTitle: "确认结束",
                            cancelTitle: "继续咨询",
                            type: .double,
                            sureHandler:
        { _ in
            if status == .advisory{
                self.endAdvisory(model, isSure: 1)
            }else{
                self.endNurse(model, isRefuse: 1)
            }
            
        }) { _ in
            if status == .advisory{
                self.endAdvisory(model, isSure: 0)
            }else{
                self.endNurse(model, isRefuse: 0)
            }
            
        }
    }
    private func endNurse(_ model: ReceiveModel, isRefuse: Int) {
        let sure = isRefuse
        AdvisoryViewModel.endNurse(diagnoseId: model.diagnoseId,
                                      isRefuse: isRefuse)
        { (errorMsg, code) in
            switch code {
            case .failure:
                HUDTool.show(message: errorMsg)
            case .success:
                if sure == 1 {
                    HUDTool.show(message: "已结束护理咨询")
                    guard let currentVc = UIViewController.current() else { return }
                    if currentVc.isKind(of: ChatViewController.classForCoder()) {
                        currentVc.navigationController?.popToRootViewController(animated: true)
                    } else {
//                        let vc = MyAdvisoryOrderFinishController(with: model.diagnoseId)
//                        (self.selectedViewController as? BaseNavigationController)?.pushViewController(vc, animated: true)
                    }
                }
            }
        }
    }
    /// 结束图文咨询
    private func endAdvisory(_ model: ReceiveModel, isSure: Int) {
        let sure = isSure
        AdvisoryViewModel.endAdvisory(doctorId: model.from,
                                      diagnoseId: model.diagnoseId,
                                      isSure: isSure)
        { (errorMsg, code) in
            switch code {
            case .failure:
                HUDTool.show(message: errorMsg)
            case .success:
                if sure == 1 {
                    HUDTool.show(message: "已结束图文咨询")
                    guard let currentVc = UIViewController.current() else { return }
                    if currentVc.isKind(of: ChatViewController.classForCoder()) {
                        NotificationCenter.default.post(name: NotiName.endAdvisory, object: nil)
                    } else {
                        let vc = MyAdvisoryOrderFinishController(with: model.diagnoseId)
                        (self.selectedViewController as? BaseNavigationController)?.pushViewController(vc, animated: true)
                    }
                }
            }
        }
    }
    
    /// 结束会议
    private func endMeeting(_ model: ReceiveModel) {
        self.pickupView?.dismiss()
        MeetingManager.shared.endMeeting()
    }
    
    /// 接视频view
    private func showPickupVideoView(_ model: ReceiveModel) {
        let pickupView = UINib.loadViewFrom(PickupVideoView.self)
        self.pickupView = pickupView
        pickupView.show(model: model)
        pickupView.pickerupClosure = { [weak self] in
            guard let self = self else { return }
            self.isSelfLeave = false
            self.isFromUMPush = false
            self.joinMeeting(with: model)
        }
        pickupView.rejectClosure = { [weak self] in
            guard let self = self else { return }
            self.isSelfLeave = true
            self.isFromUMPush = false
            self.endMeeting(model)
        }
    }
    
    func joinMeeting(with model: ReceiveModel) {
        // TODO: CL
//        MeetingManager.shared.joinMeeting(self, model: model)
    }
}

// MARK: - 推送消息跳转
extension MainViewController {
    func pushChatVc(_ model: YSGNotiMessageModel) {
        guard let currentVc = UIViewController.current() else { return }
        
        if currentVc.isKind(of: ChatViewController.classForCoder()) { return }
        
        let chatVc = ChatViewController(with: model.diagnoseId)
        currentVc.navigationController?.pushViewController(chatVc, animated: true)
    }
    
    func getYSXVideoInfo(_ model: YSGNotiMessageModel) {
        model.chatVideoMsgPush(diagnoseId: model.diagnoseId,
                               conferenceId: model.conferenceID,
                               conferenceNum: model.conferenceNum,
                               phoneId: model.phoneId,
                               meetingType: model.meetingType) { (ysxModel, errorMsg) in
            if errorMsg != nil {
                HUDTool.showError(message: errorMsg)
                return
            }
            
            guard let ysxM = ysxModel else { return }
            self.messageModel = ysxM
        }
    }
    
    func pushConsultationRoomVc(at index: Int) {
        guard let currentVc = UIViewController.current() else { return }
        
        if currentVc.isKind(of: ChatViewController.classForCoder()) { return }
        
        if currentVc.isKind(of: ConsultationRoomController.classForCoder()) {
            let selectedVc = currentVc as! ConsultationRoomController
            selectedVc.segmented.selectItemAt(index: index)
            return
        }
        
        if currentVc.isKind(of: HomeViewController.classForCoder()) ||
            currentVc.isKind(of: ReportViewController.classForCoder()) ||
            currentVc.isKind(of: ProfileViewController.classForCoder()) {
            selectedIndex = 1
            guard let selectedNav = viewControllers?[selectedIndex] as? BaseNavigationController,
                let selectedVc = selectedNav.visibleViewController as? ConsultationRoomController else { return }
            selectedVc.selectedIndex = index
        } else {
            tabBar.isHidden = false
            selectedIndex = 1
            currentVc.navigationController?.popToRootViewController(animated: true)
            guard let selectedNav = viewControllers?[selectedIndex] as? BaseNavigationController,
                let selectedVc = selectedNav.visibleViewController as? ConsultationRoomController else { return }
            selectedVc.selectedIndex = index
        }
    }
    
    func pushOrderCancelList() {
        guard let currentVc = UIViewController.current() else { return }
        
        let orderVc = MyAdvisoryOrderController(with: .cancel)
        orderVc.title = "已取消"
        currentVc.navigationController?.pushViewController(orderVc, animated: true)
    }
}
